package com.youxin.chat.pay.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youxin.chat.pay.entity.dto.PayTemplate;
import com.youxin.chat.pay.enums.OrderSourceEnum;
import com.youxin.chat.pay.mapper.*;
import com.youxin.chat.pay.model.*;
import com.youxin.chat.pay.service.manager.ImManager;
import com.youxin.chat.pay.service.rpc.UserService;
import com.youxin.chat.user.dto.UserInfoDto;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * description: TemplateServiceImpl <br>
 * date: 2020/2/29 16:36 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private CommonOrderMapper commonOrderMapper;

    @Resource
    private UserTransferMapper userTransferMapper;

    @Resource
    private BankInfoMapper bankInfoMapper;

    @Resource
    private ChannelOrderMapper channelOrderMapper;

    @Resource
    private UserCardMapper userCardMapper;

    @Resource
    private UserCashMapper userCashMapper;

    @Resource
    private ChannelCashMapper channelCashMapper;

    @Resource
    private UserService userService;

    @Resource
    private ImManager imManager;

    private UserInfoDto getUserInfo(){
        UserInfoDto userInfoDto = userService.getByUserNo("10000");
        return userInfoDto;
    }

    private String getBankName(String bankCode){
        BankInfo bankInfo = bankInfoMapper.selectOne(new LambdaQueryWrapper<BankInfo>().eq(BankInfo::getBankCode,bankCode));
        return Optional.ofNullable(bankInfo).map(BankInfo::getBankName).orElse("");
    }

    @Override
    public void sendRedPackExpireMessage(String orderNo) {
        CommonOrder commonOrder = commonOrderMapper.selectByOrderNo(orderNo);
        UserInfoDto userInfoDto = getUserInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("userNo", userInfoDto.getUserNo());
        map.put("nickName", userInfoDto.getNickName());
        map.put("avatar", userInfoDto.getAvatar());
        map.put("title","红包退款通知");
        map.put("opTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("amount", commonOrder.getOrderAmount());
        map.put("orderNo", commonOrder.getOrderNo());
        map.put("remark", commonOrder.getOrderRemark());
        map.put("finishTime", commonOrder.getOpTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("source", commonOrder.getOrderSource());
        map.put("feeType", commonOrder.getFeeType());
        List<PayTemplate> list = new ArrayList<>();
        PayTemplate amountTemplate = new PayTemplate("amount","退款金额",commonOrder.getOrderAmount().divide( new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP).toPlainString()+"元",1);
        PayTemplate payTypeTemplate = new PayTemplate("refundType","退款方式","退回红包",2);
        PayTemplate timeTemplate = new PayTemplate("finishTime","到账时间", commonOrder.getOpTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),3);
        PayTemplate orderNoTemplate = new PayTemplate("orderNo","交易单号", orderNo,4);
        PayTemplate reasonTemplate = new PayTemplate("reason","退款原回", "尤信红包超过24小时未被领取",5);
        list.add(amountTemplate);
        list.add(payTypeTemplate);
        list.add(timeTemplate);
        list.add(orderNoTemplate);
        list.add(reasonTemplate);
        imManager.sendPayMsg(commonOrder.getUserNo(),map, JSONObject.toJSONString(list));
    }

    @Override
    public void sendChargeSuccMessage(String orderNo) {
        ChannelOrder channelOrder = channelOrderMapper.selectOne(
                new LambdaQueryWrapper<ChannelOrder>().eq(ChannelOrder::getChannelOrderNo, orderNo));
        if(channelOrder == null){
            return;
        }
        String bankName = "";
        UserCard userCard = userCardMapper.selectByCardNoAndUserNo(channelOrder.getUserNo(),channelOrder.getCardNo());
        if(userCard!= null){
            bankName = getBankName(userCard.getBankCode());
            bankName += "(" + userCard.getCardNo().substring(userCard.getCardNo().length()-4) +")";
        }
        UserInfoDto userInfoDto = getUserInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("userNo", userInfoDto.getUserNo());
        map.put("nickName", userInfoDto.getNickName());
        map.put("avatar", userInfoDto.getAvatar());
        map.put("title","充值成功通知");
        map.put("opTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("source", OrderSourceEnum.PAY.getStatus());
        List<PayTemplate> list = new ArrayList<>();
        PayTemplate amountTemplate = new PayTemplate("amount","充值金额",channelOrder.getRechargeAmount().divide( new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP).toPlainString()+"元",1);
        PayTemplate payTypeTemplate = new PayTemplate("payType","支付方式",bankName,2);
        PayTemplate timeTemplate = new PayTemplate("chargeTime","充值时间", channelOrder.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),3);
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String finishTime = timeFormat.format(channelOrder.getSuccTime());
        PayTemplate finishTimeTemplate = new PayTemplate("chargeTime","到帐时间", finishTime,4);
        PayTemplate orderNoTemplate = new PayTemplate("orderNo","交易单号", channelOrder.getRechrageNo(),5);
        PayTemplate remarkTemplate = new PayTemplate("remark","备注", "您可以在\"我-我的钱包\"内查看零钱明细",6);
        list.add(amountTemplate);
        list.add(payTypeTemplate);
        list.add(timeTemplate);
        list.add(finishTimeTemplate);
        list.add(orderNoTemplate);
        list.add(remarkTemplate);
        imManager.sendPayMsg(channelOrder.getUserNo(),map, JSONObject.toJSONString(list));
    }

    @Override
    public void sendDefraySuccMessage(String orderNo) {
        ChannelCash channelCash = channelCashMapper.selectOne(new LambdaQueryWrapper<ChannelCash>().eq(ChannelCash::getCashNo,orderNo));
        UserCash userCash = userCashMapper.selectOne(new LambdaQueryWrapper<UserCash>().eq(UserCash::getCashNo, orderNo));
        if(channelCash == null){
            return;
        }
        if(userCash == null){
            return;
        }
        String bankName = "";
        UserCard userCard = userCardMapper.selectByCardNoAndUserNo(channelCash.getUserNo(),channelCash.getCardNo());
        if(userCard!= null){
            bankName = getBankName(userCard.getBankCode());
            bankName += "(" + userCard.getCardNo().substring(userCard.getCardNo().length()-4) +")";
        }
        UserInfoDto userInfoDto = getUserInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("userNo", userInfoDto.getUserNo());
        map.put("nickName", userInfoDto.getNickName());
        map.put("avatar", userInfoDto.getAvatar());
        map.put("title","提现成功通知");
        map.put("opTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("source", OrderSourceEnum.PAY.getStatus());
        List<PayTemplate> list = new ArrayList<>();
        String serviceFee = userCash.getCashAmount().subtract(channelCash.getCashAmount()).divide( new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP).toPlainString();
        PayTemplate amountTemplate = new PayTemplate("amount","提现金额",userCash.getCashAmount().divide( new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP).toPlainString()+"元",1);
        PayTemplate feeTemplate = new PayTemplate("fee","服务费",serviceFee+"元",2);
        PayTemplate reAmountTemplate = new PayTemplate("reAmount","到账金额",channelCash.getCashAmount().divide( new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP).toPlainString()+"元",3);

        PayTemplate payTypeTemplate = new PayTemplate("cashBank","提现银行",bankName,4);
        PayTemplate timeTemplate = new PayTemplate("defrayTime","提现时间", userCash.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),5);
        PayTemplate finishTimeTemplate = new PayTemplate("finishTime","到帐时间", channelCash.getFinishTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),6);
        PayTemplate orderNoTemplate = new PayTemplate("orderNo","交易单号", userCash.getCashNo(),7);
        PayTemplate remarkTemplate = new PayTemplate("remark","备注", "您的零钱提现已到账至银行卡",8);
        list.add(amountTemplate);
        list.add(feeTemplate);
        list.add(reAmountTemplate);
        list.add(payTypeTemplate);
        list.add(timeTemplate);
        list.add(finishTimeTemplate);
        list.add(orderNoTemplate);
        list.add(remarkTemplate);
        imManager.sendPayMsg(userCash.getUserNo(),map, JSONObject.toJSONString(list));
    }

    @Override
    public void sendPaySuccMessage(String orderNo) {
        UserTransfer userTransfer = userTransferMapper.selectOne(new LambdaQueryWrapper<UserTransfer>().eq(UserTransfer::getOrderNo,orderNo).eq(UserTransfer::getFeeType,1));
        if(userTransfer == null){
            return;
        }
        UserInfoDto userInfoDto = getUserInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("userNo", userInfoDto.getUserNo());
        map.put("nickName", userInfoDto.getNickName());
        map.put("avatar", userInfoDto.getAvatar());
        map.put("title","扫码付款通知");
        map.put("opTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("source", OrderSourceEnum.PAY_CODE_TRANSFER.getStatus());
        List<PayTemplate> list = new ArrayList<>();
        PayTemplate amountTemplate = new PayTemplate("amount","付款金额",userTransfer.getAmount().divide( new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP).toPlainString()+"元",1);
        UserInfoDto toUserInfo = userService.getByUserNo(userTransfer.getToUserNo());
        String userName = Optional.ofNullable(toUserInfo).map(UserInfoDto::getNickName).orElse("");
        PayTemplate receiveUserTemplate = new PayTemplate("fee","收款方",userName,2);

        PayTemplate statusTemplate = new PayTemplate("status","交易状态","支付成功，对方已收款",3);
        PayTemplate timeTemplate = new PayTemplate("transferTime","付款时间", userTransfer.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),4);
        PayTemplate typeTemplate = new PayTemplate("payType","支付方式", "零钱付款",5);
        PayTemplate orderNoTemplate = new PayTemplate("orderNo","交易单号", userTransfer.getId(),6);
        PayTemplate remarkTemplate = new PayTemplate("remark","备注", Optional.ofNullable(userTransfer.getRemark()).orElse("无"),7);

        list.add(amountTemplate);
        list.add(receiveUserTemplate);
        list.add(statusTemplate);
        list.add(timeTemplate);
        list.add(typeTemplate);
        list.add(orderNoTemplate);
        list.add(remarkTemplate);
        imManager.sendPayMsg(userTransfer.getFromUserNo(),map, JSONObject.toJSONString(list));
    }

    @Override
    public void sendReceiveMessage(String orderNo) {
        UserTransfer userTransfer =  userTransferMapper.selectOne(new LambdaQueryWrapper<UserTransfer>().eq(UserTransfer::getOrderNo,orderNo).eq(UserTransfer::getFeeType,0));
        if(userTransfer == null){
            return;
        }
        UserInfoDto userInfoDto = getUserInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("userNo", userInfoDto.getUserNo());
        map.put("nickName", userInfoDto.getNickName());
        map.put("avatar", userInfoDto.getAvatar());
        map.put("title","收款到帐通知");
        map.put("opTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("source", OrderSourceEnum.PAY_CODE_RECEIVE.getStatus());
        List<PayTemplate> list = new ArrayList<>();
        PayTemplate amountTemplate = new PayTemplate("amount","收款金额",userTransfer.getAmount().divide( new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP).toPlainString()+"元",1);
        UserInfoDto fromUserInfo = userService.getByUserNo(userTransfer.getFromUserNo());

        String userName = Optional.ofNullable(fromUserInfo).map(UserInfoDto::getNickName).orElse("");

        PayTemplate receiveUserTemplate = new PayTemplate("fee","付款方",userName,2);

        PayTemplate statusTemplate = new PayTemplate("status","交易状态","收款成功，已存入零钱",3);
        PayTemplate timeTemplate = new PayTemplate("transferTime","付款时间", userTransfer.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),4);
        PayTemplate typeTemplate = new PayTemplate("payType","支付方式", "零钱收款",5);

        PayTemplate orderNoTemplate = new PayTemplate("orderNo","交易单号", userTransfer.getId(),6);
        PayTemplate remarkTemplate = new PayTemplate("remark","备注", Optional.ofNullable(userTransfer.getRemark()).orElse("无"),7);

        list.add(amountTemplate);
        list.add(receiveUserTemplate);
        list.add(statusTemplate);
        list.add(timeTemplate);
        list.add(typeTemplate);
        list.add(orderNoTemplate);
        list.add(remarkTemplate);
        imManager.sendPayMsg(userTransfer.getToUserNo(),map, JSONObject.toJSONString(list));
    }
}
